package cn.edu.tju.wallet.service;

import cn.edu.tju.wallet.domain.RechargeRule;
import cn.edu.tju.wallet.domain.RechargeRule.RuleStatus;
import cn.edu.tju.wallet.dto.RechargeRuleDTO;
import cn.edu.tju.wallet.repository.RechargeRuleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class RechargeRuleService {

    @Autowired
    private RechargeRuleRepository rechargeRuleRepository;

    /**
     * 创建充值规则
     */
    @Transactional
    public RechargeRule createRechargeRule(RechargeRuleDTO dto) {
        RechargeRule rule = new RechargeRule();
        rule.setName(dto.getName());
        rule.setMinAmount(dto.getMinAmount());
        rule.setBonusAmount(dto.getBonusAmount());
        rule.setBonusRate(dto.getBonusRate());
        rule.setStartTime(dto.getStartTime() != null ? dto.getStartTime() : LocalDateTime.now());
        rule.setEndTime(dto.getEndTime());
        rule.setStatus(RuleStatus.ACTIVE);
        rule.setPriority(dto.getPriority() != null ? dto.getPriority() : 0);
        return rechargeRuleRepository.save(rule);
    }

    /**
     * 更新充值规则（完全遵循指南代码，补全所有字段）
     */
    @Transactional
    public RechargeRule updateRechargeRule(Long id, RechargeRuleDTO dto) {
        RechargeRule rule = rechargeRuleRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("规则不存在"));
        // 更新字段
        rule.setName(dto.getName());
        rule.setMinAmount(dto.getMinAmount());
        rule.setBonusAmount(dto.getBonusAmount());
        rule.setBonusRate(dto.getBonusRate());
        rule.setStartTime(dto.getStartTime() != null ? dto.getStartTime() : rule.getStartTime());
        rule.setEndTime(dto.getEndTime());
        rule.setPriority(dto.getPriority() != null ? dto.getPriority() : rule.getPriority());
        return rechargeRuleRepository.save(rule);
    }

    /**
     * 删除充值规则
     */
    @Transactional
    public void deleteRechargeRule(Long id) {
        rechargeRuleRepository.deleteById(id);
    }

    /**
     * 查询所有规则
     */
    public List<RechargeRule> getAllRules() {
        return rechargeRuleRepository.findAll();
    }
}